<template>
  <div class="app-container">
    <div id="allmap"></div>
  </div>
</template>
<script>
export default {
  props: ['locationName'],
  watch: {
    locationName: {
      handler: function(newVal) {
        this.getInfo(newVal)
      },
      deep: true
    }
  },
  data() {
    return {
      map: null,
      lng: '113.00410110444222', //经度
      lat: '28.1388889763142' //纬度
    }
  },
  mounted() {
    this.init()
    this.addOverlay('长沙市中南林业科技大学')
  },
  methods: {
    init() {
      // 百度地图API功能
      var map = new BMap.Map('allmap') // 创建Map实例
      map.centerAndZoom(new BMap.Point(this.lng, this.lat), 15) // 初始化地图,设置中心点坐标和地图级别
      map.enableScrollWheelZoom(true) //开启鼠标滚轮缩放
      map.addEventListener('click',param=>{
        this.lng = param.Ag.lng
        this.lat = param.Ag.lat
        this.addOverlay('')
        this.$emit('getLoc',{
          lng:this.lng,
          lat:this.lat
        })
      })
      this.map = map
    },
    getInfo(locationName) {
      if (locationName == '') {
        locationName = '长沙市中南林业科技大学'
      }
      var obj = {
        address: locationName,
        output: 'json',
        ak: 'dS4Qs3jxH5n6GqdoK1t7nXKzA8GGFbrE'
      }
      this.$jsonp('http://api.map.baidu.com/geocoding/v3/', obj).then(
        (res) => {
          this.lng = res.result.location.lng
          this.lat = res.result.location.lat
          this.addOverlay(locationName)
          this.$emit('getLoc',{
            lng:this.lng,
            lat:this.lat
          })
        }
      )
    },
    addOverlay(locationName) {
      const point = new BMap.Point(this.lng, this.lat)
      this.map.clearOverlays()
      this.map.setCenter(point)
      this.map.addOverlay(new BMap.Marker(point, { title: locationName }))
    }
  }
}
</script>
<style>
#allmap {
  width: 200px;
  height: 200px;
}

.anchorBL {
  display: none;
}

.BMap_cpyCtrl {
  display: none;
}
</style>
